import { defineStore } from "pinia";
import * as apis from "@/api/category";
import type {
  ILevel1Category,
  ILevel2Category,
  ILevel3Category,
} from "@/api/category";
interface ICategorySelectorState {
  category1Id: number | string;
  category2Id: number | string;
  category3Id: number | string;
  category1: ILevel1Category[];
  category2: ILevel2Category[];
  category3: ILevel3Category[];
}
export const useCategorySelectorStore = defineStore<
  string,
  ICategorySelectorState,
  any,
  {
    getCategory1: () => Promise<any>;
    getCategory2: () => Promise<any>;
    getCategory3: () => Promise<any>;
  }
>("categorySelector", {
  state() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      category1: [],
      // this.category2 是否清空不重要，因为下面会获取到 res 并覆盖 category2 的
      category2: [],
      category3: [],
    };
  },
  actions: {
    async getCategory1() {
      try {
        const res = await apis.requestCategory1();
        this.category1 = res;
      } catch (e) {}
    },
    async getCategory2() {
      this.category2Id = "";
      this.category3Id = "";
      // this.category2 是否清空不重要，因为下面会获取到 res 并覆盖 category2 的
      this.category3 = [];
      try {
        const res = await apis.requestCategory2(this.category1Id as number);
        this.category2 = res;
      } catch (e) {}
    },
    async getCategory3() {
      this.category3Id = "";
      try {
        const res = await apis.requestCategory3(this.category2Id as number);
        this.category3 = res;
      } catch (e) {}
    },
  },
});
